<template>
    <div class="page-container">
        <!-- Search Card -->
        <div class="search-card">
            <div class="card-header">
                <span class="card-title">查询条件</span>
            </div>
            <div class="search-section">
                <el-form :model="searchForm" class="query-form" label-position="top" inline>
                    <el-form-item label="调查期">
                        <el-date-picker
                            v-model="searchForm.investigateTime"
                            type="month"
                            placeholder="选择调查期"
                            format="YYYY-MM"
                            value-format="YYYY-MM"
                            clearable
                            class="custom-input"
                            style="width: 200px"
                        />
                    </el-form-item>
                    <div class="form-actions">
                        <el-button @click="resetSearch" class="btn-secondary" round>重置</el-button>
                        <el-button
                            type="primary"
                            @click="searchPeriods"
                            class="btn-primary-theme"
                            round
                        >
                            <el-icon class="mr-1"><Search /></el-icon>查询
                        </el-button>
                        <el-button
                            type="success"
                            @click="showAddDialog"
                            class="btn-success-theme"
                            round
                        >
                            <el-icon class="mr-1"><Plus /></el-icon>添加调查期
                        </el-button>
                    </div>
                </el-form>
            </div>
        </div>

        <!-- Table Card -->
        <div class="table-card">
            <div class="card-header">
                <span class="card-title">调查期列表</span>
                <span class="section-subtitle"
                    >共 <span class="highlight-num">{{ pagination.total }}</span> 条记录</span
                >
            </div>

            <el-table
                v-loading="loading"
                :data="periodList"
                style="width: 100%"
                class="modern-table"
                row-key="periodId"
                :header-cell-style="{
                    background: '#f8fafc',
                    color: '#475569',
                    fontWeight: '700',
                    fontSize: '13px',
                    height: '56px',
                    textAlign: 'center',
                }"
                :cell-style="{ textAlign: 'center', padding: '12px 0' }"
            >
                <el-table-column prop="periodId" label="ID" width="100" align="center">
                    <template #default="{ row }">
                        <span class="cell-text font-mono">{{ row.periodId }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="investigateTime"
                    label="调查期标识"
                    width="140"
                    align="center"
                >
                    <template #default="{ row }">
                        <el-tag effect="light" round>{{ row.investigateTime }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="填报时间范围" min-width="320" align="center">
                    <template #default="{ row }">
                        <div class="time-range">
                            <span class="timestamp-text">{{
                                formatDateTime(row.periodStartTime)
                            }}</span>
                            <span class="separator">至</span>
                            <span class="timestamp-text">{{
                                formatDateTime(row.periodEndTime)
                            }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="enterpriseCount" label="企业总数" width="120" align="center">
                    <template #default="{ row }">
                        <span class="cell-primary-text">{{ row.enterpriseCount }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="createdAt" label="创建时间" width="180" align="center">
                    <template #default="{ row }">
                        <span class="timestamp-text">{{ formatDateTime(row.createdAt) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" fixed="right" align="center">
                    <template #default="scope">
                        <div class="action-group">
                            <el-button
                                type="primary"
                                link
                                class="action-btn"
                                @click="showEditDialog(scope.row)"
                                >编辑</el-button
                            >
                            <div class="divider"></div>
                            <el-button
                                type="danger"
                                link
                                class="action-btn danger"
                                @click="handleDelete(scope.row)"
                                >删除</el-button
                            >
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <!-- Pagination -->
            <div class="pagination-wrapper">
                <el-pagination
                    v-model:current-page="pagination.page"
                    v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </div>

        <!-- Add/Edit Dialog -->
        <el-dialog
            v-model="dialogVisible"
            :title="isEdit ? '编辑调查期' : '添加调查期'"
            width="600px"
            class="custom-dialog"
            align-center
        >
            <el-form
                ref="periodFormRef"
                :model="periodForm"
                :rules="periodRules"
                label-position="top"
                class="modern-form"
            >
                <el-form-item v-if="isEdit" label="调查期ID">
                    <el-input v-model="periodForm.periodId" disabled class="custom-input" />
                </el-form-item>
                <el-form-item label="调查期标识" prop="investigateTime">
                    <el-date-picker
                        v-model="periodForm.investigateTime"
                        type="month"
                        placeholder="选择调查期"
                        format="YYYY-MM"
                        value-format="YYYY-MM"
                        :disabled="isEdit"
                        class="custom-input"
                        style="width: 100%"
                    />
                </el-form-item>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="填报开始时间" prop="periodStartTime">
                            <el-date-picker
                                v-model="periodForm.periodStartTime"
                                type="datetime"
                                placeholder="选择开始时间"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                class="custom-input"
                                style="width: 100%"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="填报结束时间" prop="periodEndTime">
                            <el-date-picker
                                v-model="periodForm.periodEndTime"
                                type="datetime"
                                placeholder="选择结束时间"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                class="custom-input"
                                style="width: 100%"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item v-if="!isEdit" label="添加连续周期">
                    <el-select
                        v-model="periodForm.continuousMonths"
                        placeholder="选择连续周期"
                        class="custom-select"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="option in continuousMonthOptions"
                            :key="option.value"
                            :label="option.label"
                            :value="option.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item v-if="isEdit" label="企业总数">
                    <el-input v-model="periodForm.enterpriseCount" disabled class="custom-input" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false" class="btn-secondary">取消</el-button>
                    <el-button type="primary" @click="submitPeriodForm" class="btn-primary-theme"
                        >确认</el-button
                    >
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus } from '@element-plus/icons-vue';
import periodApi from '../../api/period.js';

// 搜索表单
const searchForm = reactive({
    investigateTime: '',
});

// 分页信息
const pagination = reactive({
    page: 1,
    pageSize: 10,
    total: 0,
});

// 调查期列表数据
const periodList = ref([]);
const loading = ref(false);

// 对话框相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const periodFormRef = ref(null);
const periodForm = reactive({
    periodId: '',
    investigateTime: '',
    periodStartTime: '',
    periodEndTime: '',
    enterpriseCount: '',
    continuousMonths: 1, // 添加连续周期字段，默认为1个月
});

// 连续周期选项
const continuousMonthOptions = ref([]);

// 初始化连续周期选项
onMounted(() => {
    getPeriodList();
    // 生成1-12月的选项
    continuousMonthOptions.value = Array.from({ length: 12 }, (_, i) => ({
        value: i + 1,
        label: `${i + 1}月`,
    }));
});

// 表单验证规则
const periodRules = {
    investigateTime: [{ required: true, message: '请选择调查期标识', trigger: 'change' }],
    periodStartTime: [{ required: true, message: '请选择填报开始时间', trigger: 'change' }],
    periodEndTime: [
        { required: true, message: '请选择填报结束时间', trigger: 'change' },
        {
            validator: (rule, value, callback) => {
                if (
                    periodForm.periodStartTime &&
                    value &&
                    new Date(value) <= new Date(periodForm.periodStartTime)
                ) {
                    callback(new Error('填报结束时间必须晚于填报开始时间'));
                } else {
                    callback();
                }
            },
            trigger: 'change',
        },
    ],
};

// 初始化加载
onMounted(() => {
    getPeriodList();
});

// 获取调查期列表
const getPeriodList = async () => {
    loading.value = true;
    try {
        const params = {
            ...searchForm,
            page: pagination.page,
            pageSize: pagination.pageSize,
        };

        // 转换参数名称，确保与后端接口一致（将驼峰命名转为下划线命名）
        const convertedParams = {
            investigateTime: params.investigateTime,
            page: params.page,
            pageSize: params.pageSize,
        };

        const res = await periodApi.getPeriodList(convertedParams);

        // 将后端返回的下划线命名转为驼峰命名
        periodList.value = (res.data.list || []).map((item) => ({
            periodId: item.periodId,
            investigateTime: item.investigateTime,
            periodStartTime: item.periodStartTime,
            periodEndTime: item.periodEndTime,
            enterpriseCount: item.enterpriseCount,
            createdAt: item.createdAt,
            updatedAt: item.updatedAt,
        }));

        pagination.total = res.data.totalCount || 0;
    } catch (error) {
        console.error('获取调查期列表失败', error);
        ElMessage.error('获取调查期列表失败');
    } finally {
        loading.value = false;
    }
};

// 显示添加对话框
const showAddDialog = () => {
    isEdit.value = false;
    resetPeriodForm();
    dialogVisible.value = true;
};

// 显示编辑对话框
const showEditDialog = async (row) => {
    isEdit.value = true;
    resetPeriodForm();

    try {
        const res = await periodApi.getPeriodDetail(row.periodId);

        // 将后端返回的下划线命名转为驼峰命名
        periodForm.periodId = res.data.periodId;
        periodForm.investigateTime = res.data.investigateTime;
        periodForm.periodStartTime = res.data.periodStartTime;
        periodForm.periodEndTime = res.data.periodEndTime;
        periodForm.enterpriseCount = res.data.enterpriseCount;

        dialogVisible.value = true;
    } catch (error) {
        console.error('获取调查期详情失败', error);
        ElMessage.error('获取调查期详情失败');
    }
};

// 重置调查期表单
const resetPeriodForm = () => {
    periodForm.periodId = '';
    periodForm.investigateTime = '';
    periodForm.periodStartTime = '';
    periodForm.periodEndTime = '';
    periodForm.enterpriseCount = '';
    periodForm.continuousMonths = 1; // 重置连续周期为默认值

    if (periodFormRef.value) {
        periodFormRef.value.resetFields();
    }
};

// 提交调查期表单
const submitPeriodForm = async () => {
    if (!periodFormRef.value) return;

    await periodFormRef.value.validate(async (valid) => {
        if (valid) {
            if (isEdit.value) {
                // 编辑模式，仅更新单个调查期
                const data = {
                    periodId: periodForm.periodId,
                    investigateTime: periodForm.investigateTime,
                    periodStartTime: periodForm.periodStartTime,
                    periodEndTime: periodForm.periodEndTime,
                };

                const result = await periodApi.updatePeriod(data);
                if (result.code != 200) {
                    ElMessage.error(result.info);
                    return;
                }
                ElMessage.success('更新调查期成功');
            } else {
                // 添加模式，处理连续周期
                try {
                    let successCount = 0;
                    const totalCount = periodForm.continuousMonths;

                    // 获取起始月份
                    const startDate = new Date(periodForm.investigateTime + '-01');

                    // 计算填报时间间隔（毫秒）
                    const startDateTime = new Date(periodForm.periodStartTime);
                    const endDateTime = new Date(periodForm.periodEndTime);
                    const fillTimeSpan = endDateTime - startDateTime;

                    // 创建所有连续的调查期
                    for (let i = 0; i < totalCount; i++) {
                        // 计算当前月份
                        const currentDate = new Date(startDate);
                        currentDate.setMonth(currentDate.getMonth() + i);
                        const year = currentDate.getFullYear();
                        const month = String(currentDate.getMonth() + 1).padStart(2, '0');
                        const investigateTime = `${year}-${month}`;

                        // 计算当前月的填报开始和结束时间
                        const currentStartDate = new Date(startDateTime);
                        const currentEndDate = new Date(endDateTime);
                        currentStartDate.setMonth(currentStartDate.getMonth() + i);
                        currentEndDate.setMonth(currentEndDate.getMonth() + i);

                        // 确保结束时间晚于开始时间
                        if (currentEndDate <= currentStartDate) {
                            currentEndDate.setTime(currentStartDate.getTime() + fillTimeSpan);
                        }

                        // 直接使用格式化好的日期时间字符串，避免时区转换问题
                        const data = {
                            investigateTime,
                            periodStartTime: formatDateForBackend(currentStartDate),
                            periodEndTime: formatDateForBackend(currentEndDate),
                        };

                        // 添加调查期
                        const result = await periodApi.addPeriod(data);
                        if (result.code == 200) {
                            successCount++;
                        }
                    }

                    ElMessage.success(`成功添加 ${successCount}/${totalCount} 个调查期`);
                } catch (error) {
                    console.error('批量添加调查期失败', error);
                    ElMessage.error('添加调查期失败');
                }
            }

            dialogVisible.value = false;
            getPeriodList(); // 重新加载数据
        }
    });
};

// 搜索调查期
const searchPeriods = () => {
    pagination.page = 1;
    getPeriodList();
};

// 重置搜索条件
const resetSearch = () => {
    searchForm.investigateTime = '';
    pagination.page = 1;
    getPeriodList();
};

// 分页大小变化
const handleSizeChange = (size) => {
    pagination.pageSize = size;
    getPeriodList();
};

// 页码变化
const handleCurrentChange = (page) => {
    pagination.page = page;
    getPeriodList();
};

// 处理删除调查期
const handleDelete = (row) => {
    ElMessageBox.confirm(`确定要删除调查期 ${row.investigateTime} 吗？`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'custom-message-box',
        confirmButtonClass: 'btn-danger-theme',
        cancelButtonClass: 'btn-secondary',
    })
        .then(async () => {
            try {
                const result = await periodApi.deletePeriod(row.periodId);
                if (result.code != 200) {
                    ElMessage.error(result.info);
                    return;
                }
                ElMessage.success('删除调查期成功');
                getPeriodList(); // 重新加载数据
            } catch (error) {
                console.error('删除调查期失败', error);
                ElMessage.error('删除调查期失败');
            }
        })
        .catch(() => {
            // 用户取消删除操作
        });
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
    if (!dateTime) return '-';
    return dateTime;
};

// 为后端格式化日期时间，避免时区转换问题
const formatDateForBackend = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
</script>

<style scoped lang="scss">
.page-container {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    padding: 24px 40px;
    color: #1e293b;
    font-family: 'Inter', sans-serif;
}

/* Header */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 40px;
    background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
    border-radius: 24px;
    color: white;
    box-shadow: 0 20px 40px -12px rgba(79, 70, 229, 0.3);
}

.page-title {
    font-size: 28px;
    font-weight: 800;
    margin: 0 0 8px 0;
    color: white;
}

.page-description {
    font-size: 15px;
    opacity: 0.9;
    margin: 0;
    font-weight: 400;
    color: white;
}

/* Search Card */
.search-card {
    background: #ffffff;
    border-radius: 16px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.02);
    margin-bottom: 24px;
    border: 1px solid rgba(241, 245, 249, 1);
    overflow: hidden;
}

.card-header {
    padding: 16px 24px;
    border-bottom: 1px solid #f1f5f9;
    background: #fafafa;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-title {
    font-size: 15px;
    font-weight: 700;
    color: #0f172a;
}

.search-section {
    padding: 24px;
}

.query-form {
    margin-bottom: 0;
    display: flex;
    flex-wrap: wrap;
    gap: 24px;
    align-items: flex-end;

    :deep(.el-form-item) {
        margin-bottom: 0;
        margin-right: 0;
        display: flex;
        flex-direction: column;

        .el-form-item__label {
            justify-content: flex-start;
            padding-bottom: 6px;
            font-size: 13px;
            font-weight: 600;
            color: #64748b;
        }
    }
}

.form-actions {
    display: flex;
    gap: 12px;
    margin-left: auto;
    align-self: flex-end;
}

/* Table Card */
.table-card {
    background: #ffffff;
    border-radius: 24px;
    box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.03);
    border: 1px solid rgba(241, 245, 249, 1);
    overflow: hidden;
    margin-bottom: 24px;
}

.section-subtitle {
    font-size: 13px;
    color: #64748b;

    .highlight-num {
        color: #4f46e5;
        font-weight: 700;
        font-size: 15px;
        padding: 0 2px;
    }
}

/* Modern Table */
.modern-table {
    border-radius: 16px;
    overflow: hidden;
    --el-table-border-color: #f1f5f9;
    --el-table-row-hover-bg-color: #f8fafc;
    --el-table-header-bg-color: #f8fafc;
}

.cell-primary-text {
    font-size: 14px;
    font-weight: 600;
    color: #0f172a;
}

.cell-text {
    font-size: 13px;
    color: #64748b;
}

.font-mono {
    font-family: 'JetBrains Mono', monospace;
}

.timestamp-text {
    font-variant-numeric: tabular-nums;
    color: #334155;
    font-size: 13px;
    font-weight: 500;
}

.time-range {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.separator {
    color: #94a3b8;
    font-size: 12px;
}

/* Buttons */
.btn-primary-theme {
    background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%) !important;
    border: none !important;
    color: white !important;
    font-weight: 600;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(79, 70, 229, 0.25);
    transition: all 0.2s ease;
    padding: 8px 20px;
}

.btn-primary-theme:hover {
    background: linear-gradient(135deg, #4338ca 0%, #4f46e5 100%) !important;
    transform: translateY(-1px);
    box-shadow: 0 8px 20px rgba(79, 70, 229, 0.35);
}

.btn-success-theme {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
    border: none !important;
    color: white !important;
    font-weight: 600;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.25);
    transition: all 0.2s ease;
    padding: 8px 20px;
}

.btn-success-theme:hover {
    background: linear-gradient(135deg, #059669 0%, #047857 100%) !important;
    transform: translateY(-1px);
    box-shadow: 0 8px 20px rgba(16, 185, 129, 0.35);
}

.btn-secondary {
    background: #fff;
    border: 1px solid #e2e8f0;
    color: #475569;
    font-weight: 500;
    border-radius: 8px;
    padding: 8px 20px;

    &:hover {
        background: #f8fafc;
        color: #1e293b;
        border-color: #cbd5e1;
    }
}

.action-btn {
    font-weight: 600;
    &.danger {
        color: #ef4444;
        &:hover {
            color: #dc2626;
        }
    }
}

.pagination-wrapper {
    padding: 16px 24px;
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #f1f5f9;
}

/* Inputs */
.custom-input,
.custom-select {
    :deep(.el-input__wrapper) {
        border-radius: 8px;
        box-shadow: 0 0 0 1px #e2e8f0 inset;
        padding: 6px 12px;
        &.is-focus {
            box-shadow: 0 0 0 2px #818cf8 inset;
        }
    }
}

/* Dialog */
:deep(.custom-dialog) {
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);

    .el-dialog__header {
        margin: 0;
        padding: 20px 24px;
        border-bottom: 1px solid #f1f5f9;
        .el-dialog__title {
            font-weight: 700;
            font-size: 18px;
            color: #0f172a;
        }
    }

    .el-dialog__body {
        padding: 32px;
    }

    .el-dialog__footer {
        padding: 20px 24px;
        border-top: 1px solid #f1f5f9;
        background-color: #f8fafc;
    }
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

.modern-form {
    :deep(.el-form-item__label) {
        font-weight: 600;
        color: #475569;
        margin-bottom: 8px;
    }
}

.action-group {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.divider {
    width: 1px;
    height: 14px;
    background: #e2e8f0;
}

.mr-1 {
    margin-right: 4px;
}
</style>

<style lang="scss">
/* Global styles for ElMessageBox */
.custom-message-box {
    border-radius: 16px !important;
    overflow: hidden;
    border: none !important;
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25) !important;
    padding-bottom: 20px !important;

    .el-message-box__header {
        padding: 20px 24px;
        border-bottom: 1px solid #f1f5f9;

        .el-message-box__title {
            font-weight: 700;
            color: #0f172a;
        }
    }

    .el-message-box__content {
        padding: 24px;
        color: #334155;
        font-size: 15px;
    }

    .el-message-box__btns {
        padding: 0 24px 0 0;

        .el-button {
            border-radius: 8px;
            font-weight: 600;
            padding: 10px 20px;
            height: auto;
        }

        .btn-primary-theme {
            background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%);
            border: none;
            color: white;

            &:hover {
                transform: translateY(-1px);
                box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
            }
        }

        .btn-danger-theme {
            background: #ef4444;
            border: none;
            color: white;

            &:hover {
                background: #dc2626;
            }
        }

        .btn-secondary {
            background: #fff;
            border: 1px solid #e2e8f0;
            color: #475569;

            &:hover {
                background: #f8fafc;
                color: #1e293b;
            }
        }
    }
}
</style>
